#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <cstdlib>

const double PI = 3.14159265358979323846;

int main() {
    int n = 1000; // 样本数
    double dx = 0.001; // x轴的步长
    int k1 = 3;  // 第一个频率索引
    int k2 = 9;  // 第二个频率索引

    // 创建数据文件
    std::ofstream sinFile1("sin_k3.dat");
    std::ofstream sinFile2("sin_k9.dat");
    std::ofstream sinDiscrete("sin_discrete.dat"); // 离散点数据文件

    // 检查文件是否成功打开
    if (!sinFile1.is_open() || !sinFile2.is_open() || !sinDiscrete.is_open()) {
        std::cerr << "无法打开文件用于写入！" << std::endl;
        return 1;
    }

    // 计算并保存正弦分量
    for (int j = 0; j < n; ++j) {
        double x = j * dx; // x轴的值
        double w1 = -sin(k1 * PI * x);
        double w2 = sin(k2 * PI * x);

        sinFile1 << x << " " << w1 << std::endl;
        sinFile2 << x << " " << w2 << std::endl;
    }

    // 计算并保存离散点
    int k=6;
    double h=1.0/k;
    std::vector<double> x_discrete(7); // 存储6个离散点的x值
    for (int i = 0; i <= k; ++i) { 
    x_discrete[i] = i *h;
    double w3 = -sin(3* x_discrete[i] * PI);
    sinDiscrete << x_discrete[i] << " " << w3 << std::endl;
}

    // 关闭文件
    sinFile1.close();
    sinFile2.close();
    sinDiscrete.close();

    // 生成 Gnuplot 脚本并执行
    std::ofstream gnuplot_script("plot.gnuplot");
    if (!gnuplot_script.is_open()) {
        std::cerr << "无法打开 Gnuplot 脚本文件用于写入！" << std::endl;
        return 1;
    }

    gnuplot_script << "# Gnuplot 脚本\n"
                   << "set terminal pngcairo size 800,600 enhanced font 'Verdana,10'\n"
                   << "set output 'sin_plot.png'\n" // 指定输出文件
                   << "set xlabel 'x'\n"
                   << "set ylabel 'y'\n"
                   << "set grid\n"
                   << "set yrange [-1.2:1.2]\n"
                   << "plot 'sin_k3.dat' using 1:2 with lines lt 1 lc rgb 'black' title 'k=" << k1 << "', \\\n"
                   << "     'sin_k9.dat' using 1:2 with lines lt 1 lc rgb 'red' title 'k=" << k2 << "', \\\n"
                   << "     'sin_discrete.dat' using 1:2 with linespoints pt 7 ps 1.5 lc rgb 'blue' title 'Discrete Points'\n";
    gnuplot_script.close();

    // 调用 Gnuplot 执行脚本
    int gnuplot_result = std::system("gnuplot plot.gnuplot");
    if (gnuplot_result != 0) {
        std::cerr << "Gnuplot 脚本执行失败！" << std::endl;
        return 1;
    }

    std::cout << "绘图完成！图像已保存为 sin_plot.png" << std::endl;

    return 0;
}